package com.example.mytayunapi.Controller;
import com.example.mytayunapi.Service.ProductImagesInfoService;
import com.example.mytayunapi.Vo.RefundProductsOrders;
import com.github.pagehelper.PageInfo;
import com.example.mytayunapi.Entity.productsInfo;
import com.example.mytayunapi.Service.productsInfoService;
import com.example.mytayunapi.Vo.UserProductImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.*;

import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("approvalproduct")


public class productsInfoController {
    @Autowired
    private productsInfoService productsinfoservice;

    //http://localhost:8080/approvalproduct/school
    @GetMapping("/school")
    public List<RefundProductsOrders> getRefundProductsOrdersBySchoolDegree(@RequestParam String School_degree) {
        return productsinfoservice.findRefundProductsOrdersBySchoolDegree(School_degree);
    }

    //http://localhost:8080/approvalproduct/delRefund
    @GetMapping("/delRefund")
    public Integer getdelRefund(@RequestParam String Refund_id){
        return productsinfoservice.deleteRefund(Refund_id);
    }


    @Autowired
    private ProductImagesInfoService productImageService;





    //http://localhost:8080/approvalproduct/add
    @PostMapping("/add")
    public ResponseEntity<String> addProduct(@RequestParam("Product_name") String productName,
                                             @RequestParam("Product_price") String productPrice,
                                             @RequestParam("category") String category,
                                             @RequestParam("subcategory") String subcategory,
                                             @RequestParam("Product_detail") String productDetail,
                                             @RequestParam("Product_status") String productStatus,
                                             @RequestParam("School_degree") String schoolDegree,
                                             @RequestParam("Product_images") List<MultipartFile> productImages) {
        try {
            // 构建产品对象
            productsInfo product = new productsInfo();
            product.setProduct_name(productName);
            product.setProduct_price(productPrice);
            product.setCategory(category);
            product.setSubcategory(subcategory);
            product.setProduct_detail(productDetail);
            product.setProduct_status(productStatus);
            product.setSchool_degree(schoolDegree);
            System.out.println("Product_status set to: " + product.getProduct_status());
            List<String> imagePaths = null;
            if (productImages != null && productImages.size() > 0) {
                // Example path; adjust to your actual path
                String imagePath = "C:/Users/1056/IdeaProjects/tayun-tayun/tayun-user-end/html/assets/imgs/productimages/";

                imagePaths = new ArrayList<>();
                for (MultipartFile file : productImages) {
                    String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                    String filePath = "assets/imgs/productimages/";
                    saveFile(file, imagePath, filename);
                    imagePaths.add(filePath + filename); // Save full path to each image
                }

                // Assuming you want to save the first image path to the main product object
                if (!imagePaths.isEmpty()) {
                    product.setProduct_image(imagePaths.get(0));
                }
            }

            productsInfo savedProduct = productsinfoservice.saveProduct(product);
            Integer productId = savedProduct.getProductId();

            productImageService.saveProductImages(productId, imagePaths);

            return ResponseEntity.ok("Product added successfully");

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save product images");
        }
    }

    private void saveFile(MultipartFile file, String path, String filename) throws IOException {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File serverFile = new File(dir, filename);
        file.transferTo(serverFile);
    }

    //分类
    //http://localhost:8080/approvalproduct/bigcategory
    @GetMapping("/bigcategory")
    public List<productsInfo> findByCategoryAndstatus(@RequestParam(required = false) String category) {
        if (category == null || category.isEmpty()) {
            // 如果 category 为空或空字符串，则返回所有产品信息
            return productsinfoservice.getInfoByReleaseStatus();
        } else {
            // 否则按照指定的 category 返回产品信息
            return productsinfoservice.findByCategoryAndstatus(category);
        }
    }

    //http://localhost:8080/approvalproduct/relatedProducts
    @GetMapping("/relatedProducts")
    public List<productsInfo> getProductsByCategory(@RequestParam String category) {
        return productsinfoservice.findByCategory(category);
    }

    //http://localhost:8080/approvalproduct/downproduct
    @GetMapping("/downproduct")
    public List<productsInfo> getDownProducts() {
        return productsinfoservice.getDownProducts();
    }

    //http://localhost:8080/approvalproduct/updatestatus
    @PostMapping("/updatestatus")
    public Integer updateProductStatus(@RequestBody productsInfo productsinfo) {
        return productsinfoservice.updateProductStatus(productsinfo);
    }

    //http://localhost:8080/approvalproduct/product
    @GetMapping("/product")
    public List<productsInfo> getInfoByReleaseStatus() {
        return productsinfoservice.getInfoByReleaseStatus(); }

    //http://localhost:8080/approvalproduct/query
    @GetMapping("/query")
    public List<UserProductImage>  getImageUserProduct(){
        return productsinfoservice.getImageUserProduct();
    }

    //http://localhost:8080/approvalproduct/queryid
    @GetMapping("queryid")
    public List<UserProductImage> getImageUserProductId(Integer Product_id){
        if (Product_id == null) {
            return Collections.emptyList();
        }else {
            return productsinfoservice.getImageUserProductId(Product_id);
        }
    }

    //http://localhost:8080/approvalproduct/update
    @PostMapping("update")
    public Integer updateProductsInfoByProductId(@RequestBody UserProductImage productsStatusInfo){
        return productsinfoservice.updateProductsInfoByProductId(productsStatusInfo);
    }

    //http://localhost:8080/approvalproduct/products_detail
    @GetMapping("/products_detail")
    public List<productsInfo> getProductsDetail(@RequestParam String Release_status){
        return productsinfoservice.getProductsInfoByReleaseStatus(Release_status);
    }

    //http://localhost:8080/approvalproduct/insert
    @PostMapping("/insert")
    public Integer insertProducts(productsInfo productsinfo){
        return productsinfoservice.insertProductsInfo(productsinfo);
    }

    //http://localhost:8080/approvalproduct/page   分页1
    @GetMapping("/page")
    public   PageInfo<UserProductImage> pageInfo(@RequestParam Integer page , @RequestParam Integer size){
        return productsinfoservice.getPageInfo(page,size);
    }//上架商品审核分页

    //http://localhost:8080/approvalproduct/pages   分页2
    @GetMapping("/pages")
    public PageInfo<productsInfo> pageInfos(@RequestParam Integer page, @RequestParam Integer size){
        return productsinfoservice.getPageInfos(page,size);
    }//在售商品分页


    //http://localhost:8080/approvalproduct/pageU   分页3
    @GetMapping("/pageU")
    public   PageInfo<productsInfo> pageInfoU(@RequestParam Integer page, @RequestParam Integer size){
        return productsinfoservice.getPageInfoU(page,size);
    }//在售商品分页

    //http://localhost:8080/approvalproduct/queryNA
    @GetMapping("/queryNA")
    public List<UserProductImage> queryNA(String Release_status){
        return productsinfoservice.getImageUserProductByReleaseStatus(Release_status);
    }

    //http://localhost:8080/approvalproduct/queryNANO
    @GetMapping("/queryNANO")
    public List<UserProductImage> queryNANO(String Release_status){
        return productsinfoservice.getImageUserProductByReleaseStatusNot(Release_status);
    }
//
    //http://localhost:8080/approvalproduct/queryStaAId
    @GetMapping("/queryStaAId")
    public List<UserProductImage> queryStaAId(@RequestParam(value ="Release_status" ,required = false) String Release_status,
                                              @RequestParam(value ="Product_id",required = false) Integer Product_id){

        if (Release_status != null && Product_id != null) {
            // 处理两个参数都为空的情况，或者抛出异常
            return productsinfoservice.getImageUserProductByReleaseStatusAndId(Release_status, Product_id);
        }else if(Release_status != null){
            return productsinfoservice.getImageUserProductByReleaseStatus(Release_status);
        }
        else if (Product_id != null) {
            // 只有 productId 不为空，执行基于 productId 的查询
            return productsinfoservice.getImageUserProductId(Product_id);
        } else {
            // 两个参数都为空的情况，抛出异常或返回空列表
            return Collections.emptyList();
        }
    }


    //http://localhost:8080/approvalproduct/queryCateAsub
    @GetMapping("/queryCateAsub")
    public List<UserProductImage> queryCateAsub(@RequestParam(value = "category",required = false) String category,
                                                @RequestParam(value = "subcategory",required = false) String subcategory,
                                                @RequestParam(value = "keyword",required = false) String keyword){
        if(category != null && subcategory != null && keyword != null) {
            return productsinfoservice.getImageUserProductByReleaseStatusAndIdProAcate(category, subcategory, keyword);
        }else if(category != null){
            return productsinfoservice.getImageUserProductByCategory(category);
        }else if(subcategory != null){
            return productsinfoservice.getImageUserProductBySubcategory(subcategory);
        }else if(keyword != null){
            return productsinfoservice.getImageUserProductByKeyword(keyword);
        }else{
            return Collections.emptyList();
        }

    }

    //http://localhost:8080/approvalproduct/queryshenhe
    @GetMapping("/queryshenhe")
    public List<UserProductImage> queryshenhe(){
        return productsinfoservice.getImageUserProductByRelease();
    }

    //http://localhost:8080/approvalproduct/querycate
    @GetMapping("/querycate")
    public List<UserProductImage> querycate(String category){
        return productsinfoservice.getImageUserProductByCategory(category);
    }

    //http://localhost:8080/approvalproduct/querysub
    @GetMapping("/querysub")
    public List<UserProductImage> querysub(String subcategory){
        return productsinfoservice.getImageUserProductBySubcategory(subcategory);
    }

    //http://localhost:8080/approvalproduct/querykey
    @GetMapping("/querykey")
    public List<UserProductImage> querykey(String keyword){
        return productsinfoservice.getImageUserProductByKeyword(keyword);
    }

    //卖家主页商品
    //http://localhost:8080/approvalproduct/getmaijia
    @GetMapping("/getmaijia")
    public List<UserProductImage> getmaijia(Integer Product_id){
        return productsinfoservice.getmaijiaProductByProductId(Product_id);
    }

    //商品搜索
    //http://localhost:8080/approvalproduct/sousuo
    @GetMapping("/sousuo")
    public List<productsInfo> sousuo(String keyword){
        return productsinfoservice.getProductByKeyword(keyword);

    }


    //数据看板
    //http://localhost:8080/approvalproduct/cake
    @GetMapping("coke")
    public  List<Map<String, Object>> getEmptyLayerData(){
        return productsinfoservice.getEchartCake();
    }

    //商品大类从index点到shop_grid_right
    //http://localhost:8080/approvalproduct/getcatgory
//    @GetMapping("/getcatgory")
//    public List<productsInfo> getcatgory(String category){
//        return productsinfoservice.getmaijiaProductByCategory(category);
//
//    }



    //    @GetMapping("/querytime")
//    public List<UserProductImage>  getProductsInfoByProductName(@RequestParam String Product_name,@RequestParam Product_time){
//        List<UserProductImage> Product_time = null;
//        if(Product_time == 0){
//            Product_name = productsInfoService.getImageUserProduct();
//        }else{
//            Product_name = productsInfoService.getProductsInfoByProductName(Product_name,Product_time);
//        }
//        return Product_time;
//    }





}